package com.yupi.yupicturebackend.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.yupicturebackend.model.dto.picture.ShareConfig;
import com.yupi.yupicturebackend.model.dto.picture.SharePosterConfig;
import com.yupi.yupicturebackend.model.dto.picture.SocialPlatform;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.List;

/**
 * 图片社交分享工具类
 * 
 * <p>支持一键分享到各大社交平台，生成分享海报等功能</p>
 * 
 * @author yupi
 */
@Slf4j
@Component
public class PictureSocialShareUtils {

    /**
     * 生成分享链接
     *
     * @param platform 社交平台
     * @param shareConfig 分享配置
     * @return 分享链接
     */
    public static String generateShareUrl(SocialPlatform platform, ShareConfig shareConfig) {
        String baseUrl = getShareBaseUrl(platform);
        if (StrUtil.isBlank(baseUrl)) {
            return null;
        }
        
        Map<String, String> params = new HashMap<>();
        
        switch (platform) {
            case WEIBO:
                params.put("title", shareConfig.getTitle());
                params.put("url", shareConfig.getUrl());
                params.put("pic", shareConfig.getImageUrl());
                break;
            case WECHAT:
                // 微信分享需要通过JS SDK，这里返回配置信息
                return generateWeChatShareConfig(shareConfig);
            case QQ:
                params.put("title", shareConfig.getTitle());
                params.put("url", shareConfig.getUrl());
                params.put("pics", shareConfig.getImageUrl());
                params.put("summary", shareConfig.getDescription());
                break;
            case TWITTER:
                params.put("text", shareConfig.getTitle() + " " + shareConfig.getDescription());
                params.put("url", shareConfig.getUrl());
                break;
            case FACEBOOK:
                params.put("u", shareConfig.getUrl());
                params.put("title", shareConfig.getTitle());
                params.put("description", shareConfig.getDescription());
                break;
            case LINKEDIN:
                params.put("url", shareConfig.getUrl());
                params.put("title", shareConfig.getTitle());
                params.put("summary", shareConfig.getDescription());
                break;
            default:
                return null;
        }
        
        return buildUrlWithParams(baseUrl, params);
    }

    /**
     * 生成分享海报
     *
     * @param posterConfig 海报配置
     * @return 海报图片字节数组
     */
    public static byte[] generateSharePoster(SharePosterConfig posterConfig) {
        try {
            // 创建海报画布
            BufferedImage poster = new BufferedImage(
                posterConfig.getWidth(), 
                posterConfig.getHeight(), 
                BufferedImage.TYPE_INT_RGB
            );
            Graphics2D g2d = poster.createGraphics();
            
            // 设置抗锯齿
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            
            // 绘制背景
            drawPosterBackground(g2d, posterConfig);
            
            // 绘制主图片
            drawMainImage(g2d, posterConfig);
            
            // 绘制标题
            drawTitle(g2d, posterConfig);
            
            // 绘制描述
            drawDescription(g2d, posterConfig);
            
            // 绘制二维码
            drawQRCode(g2d, posterConfig);
            
            // 绘制装饰元素
            drawDecorations(g2d, posterConfig);
            
            // 绘制版权信息
            drawCopyright(g2d, posterConfig);
            
            g2d.dispose();
            
            // 转换为字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(poster, "PNG", baos);
            return baos.toByteArray();
            
        } catch (Exception e) {
            log.error("生成分享海报失败", e);
            return null;
        }
    }

    /**
     * 批量生成多平台分享链接
     *
     * @param platforms 平台列表
     * @param shareConfig 分享配置
     * @return 平台->分享链接映射
     */
    public static Map<SocialPlatform, String> generateMultiPlatformShareUrls(
            List<SocialPlatform> platforms, ShareConfig shareConfig) {
        Map<SocialPlatform, String> shareUrls = new HashMap<>();
        
        for (SocialPlatform platform : platforms) {
            String shareUrl = generateShareUrl(platform, shareConfig);
            if (StrUtil.isNotBlank(shareUrl)) {
                shareUrls.put(platform, shareUrl);
            }
        }
        
        return shareUrls;
    }

    /**
     * 生成短链接
     *
     * @param originalUrl 原始链接
     * @return 短链接
     */
    public static String generateShortUrl(String originalUrl) {
        try {
            // 这里可以集成短链接服务，如新浪短链接、百度短链接等
            JSONObject requestBody = new JSONObject();
            requestBody.set("url", originalUrl);
            
            // 模拟短链接服务调用
            // HttpResponse response = HttpRequest.post("SHORT_URL_API")
            //     .header("Content-Type", "application/json")
            //     .body(requestBody.toString())
            //     .execute();
            
            // 模拟返回短链接
            return "https://t.cn/" + generateRandomString(6);
            
        } catch (Exception e) {
            log.error("生成短链接失败: {}", originalUrl, e);
            return originalUrl;
        }
    }

    /**
     * 生成分享统计报告
     *
     * @param shareUrl 分享链接
     * @param timeRange 时间范围（天）
     * @return 统计报告
     */
    public static Map<String, Object> generateShareReport(String shareUrl, int timeRange) {
        Map<String, Object> report = new HashMap<>();
        
        try {
            // 模拟统计数据
            report.put("totalClicks", (int) (Math.random() * 1000));
            report.put("uniqueVisitors", (int) (Math.random() * 500));
            report.put("shareCount", (int) (Math.random() * 100));
            report.put("conversionRate", Math.random() * 0.1);
            
            // 按平台统计
            Map<String, Integer> platformStats = new HashMap<>();
            platformStats.put("微博", (int) (Math.random() * 200));
            platformStats.put("微信", (int) (Math.random() * 300));
            platformStats.put("QQ", (int) (Math.random() * 150));
            report.put("platformStats", platformStats);
            
            // 时间趋势
            List<Map<String, Object>> timeTrend = new ArrayList<>();
            for (int i = 0; i < timeRange; i++) {
                Map<String, Object> dayData = new HashMap<>();
                dayData.put("date", DateUtil.offsetDay(new Date(), -i));
                dayData.put("clicks", (int) (Math.random() * 50));
                timeTrend.add(dayData);
            }
            report.put("timeTrend", timeTrend);
            
        } catch (Exception e) {
            log.error("生成分享统计报告失败: {}", shareUrl, e);
        }
        
        return report;
    }

    /**
     * 自动发布到社交平台
     *
     * @param platform 社交平台
     * @param shareConfig 分享配置
     * @param accessToken 访问令牌
     * @return 发布结果
     */
    public static boolean autoPublishToSocial(SocialPlatform platform, ShareConfig shareConfig, String accessToken) {
        try {
            String apiUrl = getPublishApiUrl(platform);
            if (StrUtil.isBlank(apiUrl)) {
                return false;
            }
            
            JSONObject requestBody = new JSONObject();
            requestBody.set("content", shareConfig.getTitle() + "\n" + shareConfig.getDescription());
            requestBody.set("image_url", shareConfig.getImageUrl());
            requestBody.set("link", shareConfig.getUrl());
            
            HttpResponse response = HttpRequest.post(apiUrl)
                .header("Authorization", "Bearer " + accessToken)
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .execute();
            
            return response.isOk();
            
        } catch (Exception e) {
            log.error("自动发布到社交平台失败: {}", platform, e);
            return false;
        }
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 获取分享基础URL
     */
    private static String getShareBaseUrl(SocialPlatform platform) {
        switch (platform) {
            case WEIBO:
                return "https://service.weibo.com/share/share.php";
            case QQ:
                return "https://connect.qq.com/widget/shareqq/index.html";
            case TWITTER:
                return "https://twitter.com/intent/tweet";
            case FACEBOOK:
                return "https://www.facebook.com/sharer/sharer.php";
            case LINKEDIN:
                return "https://www.linkedin.com/sharing/share-offsite/";
            default:
                return null;
        }
    }

    /**
     * 生成微信分享配置
     */
    private static String generateWeChatShareConfig(ShareConfig shareConfig) {
        JSONObject config = new JSONObject();
        config.set("title", shareConfig.getTitle());
        config.set("desc", shareConfig.getDescription());
        config.set("link", shareConfig.getUrl());
        config.set("imgUrl", shareConfig.getImageUrl());
        return config.toString();
    }

    /**
     * 构建带参数的URL
     */
    private static String buildUrlWithParams(String baseUrl, Map<String, String> params) {
        StringBuilder url = new StringBuilder(baseUrl);
        boolean first = true;
        
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first) {
                url.append("?");
                first = false;
            } else {
                url.append("&");
            }
            url.append(entry.getKey()).append("=").append(URLUtil.encode(entry.getValue()));
        }
        
        return url.toString();
    }

    /**
     * 绘制海报背景
     */
    private static void drawPosterBackground(Graphics2D g2d, SharePosterConfig config) {
        if (StrUtil.isNotBlank(config.getBackgroundImageUrl())) {
            try {
                BufferedImage bgImage = ImageIO.read(new URL(config.getBackgroundImageUrl()));
                g2d.drawImage(bgImage, 0, 0, config.getWidth(), config.getHeight(), null);
            } catch (IOException e) {
                log.warn("加载背景图片失败，使用纯色背景");
                drawSolidBackground(g2d, config);
            }
        } else {
            drawSolidBackground(g2d, config);
        }
    }

    /**
     * 绘制纯色背景
     */
    private static void drawSolidBackground(Graphics2D g2d, SharePosterConfig config) {
        Color bgColor = Color.decode(config.getBackgroundColor());
        g2d.setColor(bgColor);
        g2d.fillRect(0, 0, config.getWidth(), config.getHeight());
    }

    /**
     * 绘制主图片
     */
    private static void drawMainImage(Graphics2D g2d, SharePosterConfig config) {
        if (StrUtil.isBlank(config.getMainImageUrl())) {
            return;
        }
        
        try {
            BufferedImage mainImage = ImageIO.read(new URL(config.getMainImageUrl()));
            int imageWidth = config.getMainImageWidth();
            int imageHeight = config.getMainImageHeight();
            int x = (config.getWidth() - imageWidth) / 2;
            int y = config.getMainImageY();
            
            g2d.drawImage(mainImage, x, y, imageWidth, imageHeight, null);
        } catch (IOException e) {
            log.error("绘制主图片失败", e);
        }
    }

    /**
     * 绘制标题
     */
    private static void drawTitle(Graphics2D g2d, SharePosterConfig config) {
        if (StrUtil.isBlank(config.getTitle())) {
            return;
        }
        
        Font titleFont = new Font(config.getTitleFontFamily(), Font.BOLD, config.getTitleFontSize());
        g2d.setFont(titleFont);
        g2d.setColor(Color.decode(config.getTitleColor()));
        
        FontMetrics fm = g2d.getFontMetrics();
        int x = (config.getWidth() - fm.stringWidth(config.getTitle())) / 2;
        int y = config.getTitleY();
        
        g2d.drawString(config.getTitle(), x, y);
    }

    /**
     * 绘制描述
     */
    private static void drawDescription(Graphics2D g2d, SharePosterConfig config) {
        if (StrUtil.isBlank(config.getDescription())) {
            return;
        }
        
        Font descFont = new Font(config.getDescriptionFontFamily(), Font.PLAIN, config.getDescriptionFontSize());
        g2d.setFont(descFont);
        g2d.setColor(Color.decode(config.getDescriptionColor()));
        
        // 处理多行文本
        String[] lines = wrapText(config.getDescription(), g2d.getFontMetrics(), config.getWidth() - 40);
        int y = config.getDescriptionY();
        
        for (String line : lines) {
            FontMetrics fm = g2d.getFontMetrics();
            int x = (config.getWidth() - fm.stringWidth(line)) / 2;
            g2d.drawString(line, x, y);
            y += fm.getHeight();
        }
    }

    /**
     * 绘制二维码
     */
    private static void drawQRCode(Graphics2D g2d, SharePosterConfig config) {
        if (StrUtil.isBlank(config.getQrCodeUrl())) {
            return;
        }
        
        try {
            // 这里应该生成二维码图片
            // BufferedImage qrCode = QRCodeUtils.generateQRCode(config.getQrCodeUrl(), 100, 100);
            // int x = config.getWidth() - 120;
            // int y = config.getHeight() - 120;
            // g2d.drawImage(qrCode, x, y, null);
            
            // 模拟绘制二维码占位符
            g2d.setColor(Color.BLACK);
            g2d.fillRect(config.getWidth() - 120, config.getHeight() - 120, 100, 100);
            g2d.setColor(Color.WHITE);
            g2d.drawString("QR", config.getWidth() - 80, config.getHeight() - 65);
            
        } catch (Exception e) {
            log.error("绘制二维码失败", e);
        }
    }

    /**
     * 绘制装饰元素
     */
    private static void drawDecorations(Graphics2D g2d, SharePosterConfig config) {
        // 绘制装饰线条
        g2d.setColor(Color.decode(config.getAccentColor()));
        g2d.setStroke(new BasicStroke(3));
        g2d.drawLine(50, config.getTitleY() + 20, config.getWidth() - 50, config.getTitleY() + 20);
    }

    /**
     * 绘制版权信息
     */
    private static void drawCopyright(Graphics2D g2d, SharePosterConfig config) {
        if (StrUtil.isBlank(config.getCopyright())) {
            return;
        }
        
        Font copyrightFont = new Font("Arial", Font.PLAIN, 12);
        g2d.setFont(copyrightFont);
        g2d.setColor(Color.GRAY);
        
        FontMetrics fm = g2d.getFontMetrics();
        int x = (config.getWidth() - fm.stringWidth(config.getCopyright())) / 2;
        int y = config.getHeight() - 20;
        
        g2d.drawString(config.getCopyright(), x, y);
    }

    /**
     * 文本换行处理
     */
    private static String[] wrapText(String text, FontMetrics fm, int maxWidth) {
        String[] words = text.split(" ");
        List<String> lines = new ArrayList<>();
        StringBuilder currentLine = new StringBuilder();
        
        for (String word : words) {
            String testLine = currentLine.length() == 0 ? word : currentLine + " " + word;
            if (fm.stringWidth(testLine) <= maxWidth) {
                currentLine = new StringBuilder(testLine);
            } else {
                if (currentLine.length() > 0) {
                    lines.add(currentLine.toString());
                    currentLine = new StringBuilder(word);
                } else {
                    lines.add(word);
                }
            }
        }
        
        if (currentLine.length() > 0) {
            lines.add(currentLine.toString());
        }
        
        return lines.toArray(new String[0]);
    }

    /**
     * 获取发布API URL
     */
    private static String getPublishApiUrl(SocialPlatform platform) {
        switch (platform) {
            case WEIBO:
                return "https://api.weibo.com/2/statuses/share.json";
            case TWITTER:
                return "https://api.twitter.com/2/tweets";
            default:
                return null;
        }
    }

    /**
     * 生成随机字符串
     */
    private static String generateRandomString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        
        return sb.toString();
    }
}
